#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <algorithm>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /* 初始化 */
    preferencesService = new PreferencesService();
    samW = new SampleWidget();
    tarW = new TargetWidget();
    preW = new Preference(this->preferencesService);
    scmW = new SlaveComputerManagement();
    wlk = new WLKService();
    weihu = new maintain();
    pass = new passWord();
    aboutSoftware = new AboutSoftware();
    experimentRestore = new ExperimentRestore();
    cusMsg = new CustomMessageBox();
    alysCfg = new AnalysisConfig(); // 数据分析配置工具栏窗口

    /* 主页设备状态数量初始化 */
    connectedDevice = 0; // 已连接
    disconnectDevice = 0; // 未连接
    runningDevice = 0; // 运行中
    errorDevice = 0; // 故障

    /* 设置字体加粗 */
    QFont expBarFont = ui->expBar->tabBar()->font();
    expBarFont.setWeight(QFont::Bold);
    expBarFont.setFamily("Alibaba PuHuiTi");
    ui->expBar->tabBar()->setFont(expBarFont);

    /* 创建实验恢复文件文件夹 */
    QString currentDirPath = QCoreApplication::applicationDirPath();
    QString currentDir = currentDirPath + "/$expRes";
    QDir dir_path(currentDir);
    if(!dir_path.exists()){
        dir_path.mkdir(currentDir);
    }

    /* 给按钮添加文字和图片，设置基本布局 */
    QLabel *newExpBtnText = new QLabel(); // 新建实验：按钮文字
    QLabel *newExpBtnIcon = new QLabel(); // 新建实验：图标
    QImage *newExpImg = new QImage(); // 新建实验：图片
    QFrame *newExpLine = new QFrame(); // 新建实验：分割线
    QVBoxLayout *newExpVLayout = new QVBoxLayout(); // 新建实验：垂直布局
    QLabel *analysisExpBtnText = new QLabel(); // 导入实验：按钮文字
    QLabel *analysisExpBtnIcon = new QLabel(); // 导入实验：图标
    QImage *analysisExpImg = new QImage(); // 导入实验：图片
    QFrame *analysisExpLine = new QFrame(); // 导入实验：分割线
    QVBoxLayout *analysisExpVLayout = new QVBoxLayout(); // 导入实验：垂直布局

    /* 设置按钮文字样式 */
    newExpBtnText->setStyleSheet("QLabel{"
                                 "max-height: 45px;"
                                 "font-size: 25px;"
                                 "font-family: 'Alibaba PuHuiTi';"
                                 "font-weight: bold;"
                                 "color: #fff;"
                                 "}");
    newExpBtnText->setText("新建实验");
    newExpBtnText->setAlignment(Qt::AlignCenter); // 文字居中
    analysisExpBtnText->setStyleSheet("QLabel{"
                                      "max-height: 45px;"
                                      "font-size: 25px;"
                                      "font-family: 'Alibaba PuHuiTi';"
                                      "font-weight: bold;"
                                      "color: #fff;"
                                      "}");
    analysisExpBtnText->setText("数据分析");
    analysisExpBtnText->setAlignment(Qt::AlignCenter); // 文字居中

    /* 添加图片 */
    newExpImg->load(QString(":image/image/new_exp.png"));
    newExpBtnIcon->setPixmap(QPixmap::fromImage(newExpImg->scaled(140, 140, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
    newExpBtnIcon->setAlignment(Qt::AlignCenter);

    analysisExpImg->load(QString(":image/image/data_analysis.png"));
    analysisExpBtnIcon->setPixmap(QPixmap::fromImage(analysisExpImg->scaled(140, 140, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
    analysisExpBtnIcon->setAlignment(Qt::AlignCenter);

    /* 设置分割线 */
    newExpLine->setFrameShape(QFrame::HLine);
    newExpLine->setFrameShadow(QFrame::Plain);
    newExpLine->setStyleSheet("QFrame {"
                              "color: #fff;"
                              "background-color: transparent;"
                              "}");

    analysisExpLine->setFrameShape(QFrame::HLine);
    analysisExpLine->setFrameShadow(QFrame::Plain);
    analysisExpLine->setStyleSheet("QFrame {"
                                   "color: #fff;"
                                   "background-color: transparent;"
                                   "}");

    /* 按钮设置布局 */
    newExpVLayout->addWidget(newExpBtnIcon);
    newExpVLayout->addWidget(newExpLine);
    newExpVLayout->addWidget(newExpBtnText);
    newExpVLayout->setMargin(0);
    newExpVLayout->setSpacing(0);
    ui->newExpBtn->setLayout(newExpVLayout);

    analysisExpVLayout->addWidget(analysisExpBtnIcon);
    analysisExpVLayout->addWidget(analysisExpLine);
    analysisExpVLayout->addWidget(analysisExpBtnText);
    analysisExpVLayout->setMargin(0);
    analysisExpVLayout->setSpacing(0);
    ui->analysisData->setLayout(analysisExpVLayout);


    /* 新建实验的QMenu */
    QMenu *newExpMenu = new QMenu();
    QAction *newExp = new QAction("新建实验", this);
    QAction *importExp = new QAction("导入实验", this);
    newExpMenu->addAction(newExp);
    newExpMenu->addAction(importExp);

    /* QMenu样式 */
    newExpMenu->setStyleSheet("QMenu::item{"
                              "width: 183px;"
                              "font-size: 20px;"
                              "font-family: 'Alibaba PuHuiTi';"
                              "padding: 5px;"
                              "}"
                              "QMenu::item::selected {"
                              "color: #000;"
                              "border: none;"
                              "background: rgba(75, 154, 250, 0.2);"
                              "}");

    ui->newExpBtn->setMenu(newExpMenu);


    /* 状态栏 */
    this->status = new QLabel();
    ui->statusbar->addWidget(status);

    /* 页面关闭按钮 */
    ui->expBar->setTabsClosable(true);

    /* 初始化QAction */
    ui->actionSave->setEnabled(false);
    ui->actionSaveAs->setEnabled(false);


    /* 主页 */
    /* 不可点击其他tab页 */
    for(int i = 0; i < 5; i++){
        ui->tabWidget->setTabEnabled(i, false);
    }
    /* 渲染当前已经连接的设备数量 */
    for(int i = 0; i < connectDeviceInfo.size(); i++){
        if(connectDeviceInfo[i].dev.status == "已连接") connectedDevice++;
        else if(connectDeviceInfo[i].dev.status == "未连接") disconnectDevice++;
        else if(connectDeviceInfo[i].dev.status == "运行中") runningDevice++;
        else if(connectDeviceInfo[i].dev.status == "故障") errorDevice++;
    }
    ui->connected->setText(QString::number(connectedDevice));
    ui->disConnected->setText(QString::number(disconnectDevice));
    ui->running->setText(QString::number(runningDevice));
    ui->malfunction->setText(QString::number(errorDevice));

    /* 新建实验 */
    connect(newExp, &QAction::triggered, this, [=](){
        this->newExperiment(); // 新建实验
        ExperimentUi *newExperiment = this->experimentList[experimentList.size()-1]; // 获取新建的实验
        LOG << "挂载前`" << newExperiment->thisExpIndex;
        newExperiment->mountPageFunc(); // 页面挂载
    });

    /* 导入实验 */
    connect(importExp, &QAction::triggered, this, &MainWindow::getWLK);

    /* 数据分析 */
    connect(ui->analysisData, &QPushButton::clicked, this, &MainWindow::getAnalysisWlk);

    /* QMenuBar 文件 */
    /* QAction 新建实验 */
    connect(ui->actionNewExp, &QAction::triggered, this, [=](){
        this->newExperiment(); // 新建实验
        ExperimentUi *newExperiment = this->experimentList[experimentList.size()-1]; // 获取新建的实验
        LOG << "挂载前`" << newExperiment->thisExpIndex;
        newExperiment->mountPageFunc(); // 页面挂载
    });
    /* QAction 导入实验 */
    connect(ui->actionImportExp, &QAction::triggered, this, &MainWindow::getWLK);
    /* QAction 保存 */
    connect(ui->actionSave, &QAction::triggered, this, [=](){
        /* 获取当前页面实验 */
        currentExperiment = experimentList[ui->expBar->currentIndex()-1];
        currentExperiment->saveWlkData();
    });
    /* QAction 另存为 */
    connect(ui->actionSaveAs, &QAction::triggered, this, [=](){
        LOG << "另存为触发";
        /* 获取当前页面实验 */
        currentExperiment = experimentList[ui->expBar->currentIndex()-1];
        currentExperiment->saveAsWlkData();
    });
    /* QAction 退出 */
    connect(ui->actionExit, &QAction::triggered, this, &QWidget::close);

    /* QMenuBar 工具 */
    /* QAction 样板库 */
    samW->setWindowModality(Qt::ApplicationModal);
    connect(ui->actionSampleSetting, &QAction::triggered, this, [=](){
        samW->show();
    });
    /* QAction 染料库 */
    tarW->setWindowModality(Qt::ApplicationModal);
    connect(ui->actionDyesetting, &QAction::triggered, this, [=](){tarW->show();});
    /* QAction 设备管理 */
    scmW->setWindowModality(Qt::ApplicationModal);
    connect(ui->actionSComputerManagement, &QAction::triggered, this, [=](){scmW->show();});
    /* QAction 偏好设置 */
    preW->setWindowModality(Qt::ApplicationModal);
    connect(ui->actionPreference, &QAction::triggered, this, [=](){preW->show();});
    /* QAction 数据分析配置 */
    alysCfg->setWindowModality(Qt::ApplicationModal);
    connect(ui->actionAnalysisConfig, &QAction::triggered, this, [=](){alysCfg->show();});
    /* QAction 维护校正 */
    connect(ui->actionMaintain, &QAction::triggered, this, [=](){
        pass->show();
    });
    /* QAction 实验恢复 */
    connect(ui->actionExperimentRestore, &QAction::triggered, this, [=](){experimentRestore->show();});

    /* QMenuBar 帮助 */
    /* QAction 软件信息 */
    connect(ui->actionSoftwareInfo, &QAction::triggered, this, [=](){
        aboutSoftware->show();
    });
    /* QAction 使用说明 */
    connect(ui->actionInstructionBook, &QAction::triggered, this, &MainWindow::downloadInstructions);

    /* 设备列表按钮 */
    connect(ui->computerManagement, &QPushButton::clicked, this, [=](){
        /* 打开设备管理菜单 */
        scmW->show();
    });

    /* 页面改变，修改当前实验 */
    connect(ui->expBar, &QTabWidget::currentChanged, this, [=](int index){
        if(index > 0){
            ui->actionSave->setEnabled(true);
            ui->actionSaveAs->setEnabled(true);
            currentExperiment = experimentList[index-1];
        }
        else {
            ui->actionSave->setEnabled(false);
            ui->actionSaveAs->setEnabled(false);
            currentExperiment = NULL;
        }
    });

    /* 实验页面关闭 */
    connect(ui->expBar, &QTabWidget::tabCloseRequested, this, &MainWindow::slotClosePage);

    /* 设备库数据改变 */
    connect(scmW, &SlaveComputerManagement::deviceStatusChanged, this, &MainWindow::renderMainWindowDevice);

    /* 数据恢复：数据回复完毕，进行实验分析 */
    connect(experimentRestore, &ExperimentRestore::analysisExperiment, this, [=](WLKData wlkImportData){
        qDebug() << "页面改变函数执行!!!!!!!!!!!!!!!!!!!!!!!!!!!";
        qDebug() << "页面活动前！！！！！！！！！！！！！！！！！！！！！！" << this->isActiveWindow() << this->isActiveWindow();
        if(!this->isActiveWindow()){
            this->activateWindow();
        }
        if(!this->hasFocus()){
            this->setFocus();
        }
        qDebug() << "页面活动后！！！！！！！！！！！！！！！！！！！！！！" << this->isActiveWindow() << this->isActiveWindow();
        qDebug() << "页面焦点！！！！！！！！！！！！！！！！！！！！！！" << this->hasFocus() << this->hasFocus();

        this->analysisWlkData(wlkImportData);

        qDebug() << "数据恢复结束";
    });

    /* 分析配置工具栏更新 */
    connect(alysCfg, &AnalysisConfig::updateAnalysisConfig, this, [=](QList<AnalysisTarget> alysTar){
        // 当前实验所在tab页下标
        int currentExpTabIndex = ui->expBar->currentIndex();

        // 更新当前页面非主页的数据分析信息
        if(currentExpTabIndex != 0){
            this->experimentList[currentExpTabIndex-1]->updateAnalysisConfig(alysTar);
        }
    });

    /* 分析设置：回传分析配置靶基因 */
    connect(alysCfg, &AnalysisConfig::sigGetAnalysisTarget, this, [=](){
        // 当前实验所在tab页下标
        int currentExpTabIndex = ui->expBar->currentIndex();

        // 更新当前页面非主页的数据分析信息
        if(currentExpTabIndex != 0){
            this->alysTar = this->experimentList[currentExpTabIndex-1]->getAnalysisTarget();
            this->alysCfg->renderTargetTable(this->alysTar); // 渲染分析配置靶基因
        }
    });

    /* 偏好设置：更新导出页数据 */
    connect(preW, &Preference::updateExportData, this, [=](){
        // 实验页总数
        int expSize = this->experimentList.size();

        // 更新所有页面页面非主页的导出信息
        for(int i = 0; i < expSize; i++){
            this->experimentList[i]->syncExportInfo();
        }

    });

}
MainWindow::~MainWindow()
{
    delete ui;
}

/* 新建实验 */
void MainWindow::newExperiment(){
    int curExpIndex = 0;

    /* 初始化QAction */
    ui->actionSave->setEnabled(true);
    ui->actionSaveAs->setEnabled(true);

    /* 显示加载中 */
    this->status->setText("加载中...");
    /* 等待渲染结束 */
    this->sleep(5);

    /* 新建实验 */
    ExperimentUi *experimentUi = new ExperimentUi();
    curExpIndex = ui->expBar->addTab(experimentUi, ""); // 添加实验到tabbar中
    /* 存储当前实验下标 */
    experimentUi->thisExpIndex = curExpIndex;

    experimentList.append(experimentUi); // 添加实验到设备列表中

    currentExperiment = experimentUi;

    /* 渲染实验名 */
    ui->expBar->setTabText(curExpIndex, experimentUi->sendExperimentName());

    /* 渲染设备 */
    experimentUi->renderActiveDevice();

    /* 新建实验时，刷新其他已有实验的设备列表 */
    for(int i = 0; i < experimentList.size()-1; i++){
        experimentList[i]->renderActiveDevice();
    }

    /* 初始化标签颜色 */
    if(experimentUi->experimentRunUi->cDevS.dev.status == "已连接"){
        ui->expBar->tabBar()->setTabTextColor(experimentList.size(), QColor(16, 0, 235));
    }
    else if(experimentUi->experimentRunUi->cDevS.dev.status == "运行中"){
        ui->expBar->tabBar()->setTabTextColor(experimentList.size(), QColor(8, 103, 0));
    }
    else if(experimentUi->experimentRunUi->cDevS.dev.status == "故障"){
        ui->expBar->tabBar()->setTabTextColor(experimentList.size(), QColor(182, 0, 0));
    }
    else {
        ui->expBar->tabBar()->setTabTextColor(experimentList.size(), Qt::black);
    }

    /* 写入对象 */
    AnalysisConfig *tAlysCfg = this->alysCfg;
    PreferencesService *preference = this->preferencesService;
    experimentUi->setObjs(tAlysCfg, preference);

    /* 渲染所有页面设备列表 */
    connect(experimentUi, &ExperimentUi::renderAllExperimentsDeviceList, this, [=](){
        for(int i = 0; i < experimentList.size(); i++){
            experimentList[i]->renderActiveDevice();
        }
    });

    /* 另存为 */
    connect(experimentUi, &ExperimentUi::uiSaveAsWlk, this, &MainWindow::saveAs);

    /* 实验运行状态更新，更新每个页面的设备列表 */
    connect(experimentUi, &ExperimentUi::updateActiveDeviceList, this, [=](){
        qDebug() << "运行";
        /* 更新主页设备显示信息 */
        this->renderMainWindowDevice();
    });

    /* 主页名称改变 */
    connect(experimentUi, &ExperimentUi::changeHomePageTabName, this, [=](QString experimentName){
        if(ui->expBar->currentIndex() != 0){
            ui->expBar->setTabText(ui->expBar->currentIndex(), experimentName);
        }
    });

    /* 设备恢复实验列表 */
    connect(experimentUi, &ExperimentUi::renderRestoreList, this, [=](){
        this->experimentRestore->renderExperimentNameList();
    });

    /* 运行状态显示在tab页上 */
    connect(experimentUi, &ExperimentUi::sigShowRunningStatus, this, [=](QString status){
        /* 当前实验所在tab页下标 */
        int currentExpTabIndex = ui->expBar->currentIndex();

        if(status == "运行"){
            ui->expBar->tabBar()->setTabTextColor(currentExpTabIndex, QColor(8, 103, 0));
        }
        else if(status == "故障"){
            ui->expBar->tabBar()->setTabTextColor(currentExpTabIndex, QColor(182, 0, 0));
        }
        else if(status == "暂停"){
            ui->expBar->tabBar()->setTabTextColor(currentExpTabIndex, QColor(255, 170, 0));
        }
        else if(status == "已连接"){
            ui->expBar->tabBar()->setTabTextColor(currentExpTabIndex, QColor(16, 0, 235));
        }
        else {
            ui->expBar->tabBar()->setTabTextColor(currentExpTabIndex, Qt::black);
        }
    });

    /* 关闭实验信号槽 */
    connect(experimentUi, &ExperimentUi::closePage, this, &MainWindow::slotChildClosePage);

    /* 页面跳转 */
    ui->expBar->setCurrentIndex(ui->expBar->count()-1);

    //    MEMORYSTATUSEX statusex;
    //    statusex.dwLength=sizeof(statusex);
    //    GlobalMemoryStatusEx(&statusex);
    //    qDebug()<<"物理内存使用率"<<statusex.dwMemoryLoad;
    //    qDebug()<<"物理内存总量"<<statusex.ullTotalPhys/1024/1024;
    //    qDebug()<<"可用物理内存"<<statusex.ullAvailPhys/1024/1024;

    this->status->clear();
}

/* 检查当前打开的wlk文件是否在其他页面也打开过（true-在其他页面打开了/false-在其他页面未打开） */
bool MainWindow::checkExistenceofWlk(QString sourceName){
    /* 遍历除最后一个实验外的所有实验，检测其源实验名是否与其他实验名称重复 */
    int expListSize = this->experimentList.size();
    QList<ExperimentUi*> expsList = this->experimentList;
    for(int i = 0; i < expListSize; i++){
        ExperimentUi *destinationExp = expsList[i]; // 取出单个实验
        QString destinationName = destinationExp->returnCurTabWlkName(); // 返回当前实验的wlk文件名称
        if(destinationName != "" && sourceName == destinationName){ // 如果目的实验实验名不为空 && 等于源实验名
            return true; // 在其他页面打开了
        }
    }
    return false; // 在其他页面未打开
}

/* 导入WLK文件 */
void MainWindow::getWLK(){
    bool isValid;
    /* 打开资源管理器 */
    if(fPath != ""){
        this->completeFilePath = QFileDialog::getOpenFileName(
                    this,
                    "导入文件",
                    this->fPath,
                    tr("Wlk Files (*.wlk)"));
    }
    else {
        this->completeFilePath = QFileDialog::getOpenFileName(
                    this,
                    "导入文件",
                    ".",
                    tr("Wlk Files (*.wlk)"));
    }

    /* 渲染数据 */
    std::tie(this->wlkImportData, isValid) = wlk->getWLKData(completeFilePath);
    if(completeFilePath != ""){
        // 获取wlk文件名称
        QStringList wlkFnList = this->completeFilePath.split("/");
        QString wlkName;
        if(wlkFnList.size() != 0){
            wlkName = wlkFnList[wlkFnList.size()-1];
        }
        // 重复打开判断
        if(this->checkExistenceofWlk(wlkName)){
            cusMsg->show(this, CMsg::CCritical, "打开实验", "您已打开实验文件，不能多次打开");
            return;
        }
        // 数据渲染
        renderWlk(wlkImportData);
    }
}

/* 导入数据分析WLK实验 */
void MainWindow::getAnalysisWlk(){
    bool isValid;
    /* 打开资源管理器 */
    if(fPath != ""){
        this->completeFilePath = QFileDialog::getOpenFileName(
                    this,
                    "导入文件",
                    this->fPath,
                    tr("Wlk Files (*.wlk)"));
    }
    else {
        this->completeFilePath = QFileDialog::getOpenFileName(
                    this,
                    "导入文件",
                    ".",
                    tr("Wlk Files (*.wlk)"));
    }

    /* 渲染数据 */
    std::tie(this->wlkImportData, isValid) = wlk->getWLKData(completeFilePath);
    if(completeFilePath != ""){
        // 获取wlk文件名称
        QStringList wlkFnList = this->completeFilePath.split("/");
        QString wlkName;
        if(wlkFnList.size() != 0){
            wlkName = wlkFnList[wlkFnList.size()-1];
        }
        // 重复打开判断
        if(this->checkExistenceofWlk(wlkName)){
            cusMsg->show(this, CMsg::CCritical, "数据分析", "您已打开实验文件，不能多次打开");
            return;
        }
        // 数据渲染
        analysisWlkData(wlkImportData);
    }
}

/* 渲染 WLK 文件 */
void MainWindow::renderWlk(WLKData wlkImportData){
    /* 新建实验 */
    this->newExperiment();
    /* 获取新建的实验 */
    ExperimentUi *newExperiment = this->experimentList[experimentList.size()-1];
    newExperiment->isImport = true;
    /* 传入渲染数据 */
    newExperiment->getWlkData(wlkImportData, this->wlk, this->completeFilePath);
}

/* 数据分析 */
void MainWindow::analysisWlkData(WLKData wlkImportData){
    LOG << "数据分析 wlkData: " << wlkImportData.experimentRemarks << wlkImportData.plateRemarks;
    /* 新建实验 */
    this->newExperiment();
    /* 获取新建的实验 */
    ExperimentUi *newExperiment = this->experimentList[experimentList.size()-1];

    newExperiment->isImport = true;

    newExperiment->update();

    /* 传入渲染数据 */
    newExperiment->analysisGetWlkData(wlkImportData, this->wlk, this->completeFilePath);
}

/* 渲染主页设备信息 */
void MainWindow::renderMainWindowDevice(){
    /* 渲染当前已经连接的设备数量 */
    connectedDevice = 0;
    disconnectDevice = 0;
    runningDevice = 0;
    errorDevice = 0;

    for(int i = 0; i < experimentList.size(); i++){
        /* 刷新每个页面的设备列表 */
        experimentList[i]->renderActiveDevice();
        /* 同步每个页面的导出偏好信息 */
        experimentList[i]->syncExportInfo();
    }

    /* 渲染当前已经连接的设备数量 */
    for(int i = 0; i < connectDeviceInfo.size(); i++){
        if(connectDeviceInfo[i].dev.status == "已连接") connectedDevice++;
        else if(connectDeviceInfo[i].dev.status == "未连接") disconnectDevice++;
        else if(connectDeviceInfo[i].dev.status == "运行中") runningDevice++;
        else if(connectDeviceInfo[i].dev.status == "故障") errorDevice++;
    }
    ui->connected->setText(QString::number(connectedDevice));
    ui->disConnected->setText(QString::number(disconnectDevice));
    ui->running->setText(QString::number(runningDevice));
    ui->malfunction->setText(QString::number(errorDevice));
}

/* 另存为 */
void MainWindow::saveAs(WLKData wlkData){
    LOG << "另存为";
    this->completeFilePath = QFileDialog::getSaveFileName(
                this,
                "保存文件",
                fPath,
                tr("Wlk Files (*.wlk)"));

    if(this->completeFilePath != ""){
        this->status->setText("文件保存中...");
        this->sleep(300);
        this->status->setText("文件保存成功");
        wlk->saveWLK(this->completeFilePath, wlkData);
        cusMsg->show(this, CMsg::CInformation, "文件保存", "文件保存成功！");
        this->status->clear();
    }
}

/* 下载 使用说明 文件 */
void MainWindow::downloadInstructions(){
    QString currentDirPath = QCoreApplication::applicationDirPath();
    QString sVurrentPath = currentDirPath + "/RT-μChip Analysis Software 1.0 使用说明书.pdf";
    QString copyDir = QFileDialog::getExistingDirectory(this, "下载文件", "c:");
    QString copyFilePath = copyDir + "/RT-μChip Analysis Software 1.0 使用说明书.pdf";
    QFile currentFile(sVurrentPath);

    if(copyDir != ""){ // 复制路径判空
        if(currentFile.copy(copyFilePath)){ // 判断是否复制成功
            cusMsg->show(this, CMsg::CInformation, "使用说明", "软件使用说明下载成功！");
        }else {
            cusMsg->show(this, CMsg::CCritical, "使用说明", "下载失败！请检查路径是否存在重名文件\n或检查源文件是否存在");
        }
    }
}

/* 休眠函数 */
void MainWindow::sleep(int msec){
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}


/* 关闭窗口事件 */
void MainWindow::closeEvent(QCloseEvent *event){
    bool isRunning = false;
    bool isYes = false;
    /* 有实验正在运行中 */
    for(int i = 0; i < connectDeviceInfo.size(); i++){
        if(connectDeviceInfo[i].dev.status == "运行中"){
            isRunning = true;
            if(QMessageBox::Yes == cusMsg->show(this, CMsg::CQuestion, "退出", "有实验正在运行中，是否退出软件？")){
                isYes = true;
            }
            break;
        }
    }

    /* 没有实验正在运行中 */
    if(!isRunning){
        if(QMessageBox::Yes == cusMsg->show(this, CMsg::CQuestion, "退出", "是否退出软件？")){
            isYes = true;
        }
    }

    /* 是否为 yes 按钮 */
    if(isYes){
        if(QMessageBox::Yes ==cusMsg->show(this, CMsg::CQuestion, "退出", "确认退出？")){
            for(int j = 0; j < connectDeviceInfo.size(); j++){
                connectDeviceInfo[j].instructionsService->m_socketClient->closeSocket();
            }
            for(int k = 0; k < experimentList.size(); k++){
                /* 运行标识位设为false */
                experimentList[k]->experimentRunUi->runFlag = false;

                if(experimentList[k]->completeFilePath == ""){
                    if(QMessageBox::Yes == cusMsg->show(this, CMsg::CQuestion, "保存", "是否保存当前实验？")){
                        experimentList[k]->saveWlkData();
                    }
                }
                else {
                    experimentList[k]->saveWlkData();
                }
            }
        }
        else {
            event->ignore();
        }
    }
    else {
        event->ignore();
    }

}

void MainWindow::slotClosePage(int index) {
    bool isYes = false;
    /* 不是主页 */
    if(index != 0){
        /* 判断当前实验正在运行 */
        if(experimentList[index-1]->currentIsRunning()){
            if(QMessageBox::Yes == cusMsg->show(this, CMsg::CQuestion, "页面关闭", "当前有实验正在运行，是否仍然关闭页面？")){
                if(QMessageBox::Yes == cusMsg->show(this, CMsg::CQuestion, "页面关闭", "确认关闭实验？")){
                    isYes = true;
                }
            }
        }
            /* 没在运行，直接跳保存实验 */
        else {
            isYes = true;
        }
    }

    if(isYes){
        if(experimentList[index-1]->completeFilePath == ""){
            if(QMessageBox::Yes == cusMsg->show(this, CMsg::CQuestion, "页面关闭", "是否保存当前实验？")){
                qDebug() << "保存前``````````````````````````````";
                experimentList[index-1]->saveWlkData();
                qDebug() << "保存后```````````````````````````````````";
            }
        }
        else {
            qDebug() << "保存前``````````````````````````````";
            experimentList[index-1]->saveWlkData();
            qDebug() << "保存后```````````````````````````````````";
        }
        /* 将运行标识位改为false */
        experimentList[index-1]->experimentRunUi->runFlag = false;
        /* 获取当前tab页面 */
        QWidget *delWidget = ui->expBar->widget(index);
        /* 停止设备 */
        qDebug() << "停止前````````````````````";
        experimentList[index-1]->closeActiveDevice();
        qDebug() << "停止后````````````````````";
        /* 休眠：等待 */
        /* 移除当前Tab页面 */
        ui->expBar->removeTab(index);
        /* 从 实验列表 中删除实验 */
        this->experimentList.removeAt(index - 1);
        /* 删除页面 */
        qDebug() << "删除页面前``````````````````";
        delete delWidget;
        qDebug() << "删除页面后``````````````````";


        qDebug() << "当前所有页面下标~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
    }
    else
        return;
}

void MainWindow::slotChildClosePage() {
    int index = ui->expBar->currentIndex();
    LOG << "slotChildClosePage index: " << index;
    experimentList[index-1]->experimentRunUi->runFlag = false;
    experimentList[index-1]->closeActiveDevice();
    ui->expBar->removeTab(index);
    QWidget *delWidget = ui->expBar->widget(index);
    delete delWidget;
    experimentList.removeAt(index-1);
}


